package com.example.graduation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.graduation.entity.Records;
import com.example.graduation.mapper.RecordsMapper;
import com.example.graduation.service.RecordsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.graduation.util.JwtUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xyc
 * @since 2022-02-11
 */
@Service
public class RecordsServiceImpl extends ServiceImpl<RecordsMapper, Records> implements RecordsService {

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private RecordsMapper recordsMapper;


    /**
     * 新增或者更新用户的足迹
     *
     * @param token
     * @param goodsId
     * @return {void}
     * @author xieyucan
     * CreateDate 2022/3/23 11:34
     */
    @Override
    public void insertUpdate(String token, Integer goodsId) {
        try {
            int userId = jwtUtil.getUserIdByToken(token);
            QueryWrapper<Records> wrapper = new QueryWrapper<>();
            wrapper.eq("goods_id", goodsId);
            Records records = recordsMapper.selectOne(wrapper);
            if (records == null) {
                Records records1 = new Records();
                records1.setUserId(userId);
                records1.setCreateTime(System.currentTimeMillis() / 1000);
                records1.setGoodsId(goodsId);
                recordsMapper.insert(records1);
            } else {
                UpdateWrapper<Records> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("goods_id", goodsId);
                records.setCreateTime(System.currentTimeMillis() / 1000);
                recordsMapper.update(records, updateWrapper);
            }
        } catch (Exception e) {
            throw new RuntimeException("操作异常");
        }
    }


    /**
     * 查找用户的最新足迹
     *
     * @param token
     * @return {@link Page< Records>}
     * @author xieyucan
     * CreateDate 2022/3/23 11:35
     */
    @Override
    public Page<Records> findUserRecords(String token, Integer page, Integer size) {
        if (page == null) {
            page = 1;
        }
        if (size == null) {
            size = 8;
        }
        try {
            int userId = jwtUtil.getUserIdByToken(token);
            QueryWrapper<Records> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId).orderByDesc("create_time");
            Page<Records> recordsPage = recordsMapper.selectPage(new Page<>(page, size), wrapper);
            return recordsPage;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("查询失败");
        }
    }
}
